<template>
	<view class="openMembership flex-column">
		<uni-nav-bar
			fixed="true"
			status-bar="true"
			left-icon="left"
			left-width="60rpx"
			right-width="0"
			:border="false"
			background-color="#f8f8f8"
			@clickLeft="onClickBack"
		>
			<view class="flex-row center-row header">
				<view class="flex-row center-row center-column">
					<image
						style="width: 66rpx; height: 36rpx; margin-left: 40rpx"
						src="https://mcdn.chatgk.com/xcx/static/images/vip/icon_nav_vip.png"
						mode="aspectFit"
					></image>
					<text class="text-nav-title">{{ name }}</text>
				</view>
				<text v-show="!userInfo.isVIP" class="text-nav-right" @tap="onClickBindingCard">绑定会员卡</text>
			</view>
		</uni-nav-bar>

		<!-- <image
			v-if="equipment == 'ios' || equipment == 'macos'"
			style="width: 100vw; height: 484rpx"
			src="https://mcdn.chatgk.com/xcx/static/images/vip/ios_vip_content_1.png"
			mode="aspectFit"
		></image>
		<image
			v-else
			style="width: 100vw; height: 484rpx"
			src="https://mcdn.chatgk.com/xcx/static/images/vip/vip_content_1.png"
			mode="aspectFit"
		></image> -->
		<image
			class="vip_noPrice_img"
			style="width: 100vw; height: 484rpx"
			src="https://mcdn.chatgk.com/xcx/static/images/vip/vip_noPrice.png"
			mode="aspectFit"
		></image>
		<div class="vip_price">
			<span v-if="equipment != 'ios' && equipment != 'macos'">
				<span class="zhiyuankaPrice">
					<span style="font-size: 40rpx">￥</span>
					<span>{{ Number.parseInt(storeInfo.zhiyuankaPrice) }}</span>
				</span>
				<span class="vipprice">
					<span style="font-size: 35rpx">￥</span>
					<span>{{ Number.parseInt(storeInfo.vipprice) }}</span>
				</span>
			</span>
		</div>
		<view v-if="!userInfo.isVIP" class="flex-column center-row lijikaitong" @tap="onClickOpenVip">
			<image
				style="width: 640rpx; height: 108rpx; margin-top: 28rpx; z-index: 1"
				src="https://mcdn.chatgk.com/xcx/static/images/midTabBar/buttonbg.png"
			></image>
			<text class="text-open-button">立即开通</text>
			<div class="lighting"></div>
		</view>
		<image
			style="width: 100vw; height: 502rpx; margin-top: 28rpx"
			src="https://mcdn.chatgk.com/xcx/static/images/vip/vip_content_2.png"
			mode="aspectFit"
		></image>
		<image
			style="width: 100vw; height: 604rpx; margin-top: 32rpx"
			src="https://mcdn.chatgk.com/xcx/static/images/vip/vip_content_3.png"
			mode="aspectFit"
		></image>
		<image
			style="width: 100vw; height: 750rpx; margin-top: 32rpx"
			src="https://mcdn.chatgk.com/xcx/static/images/vip/vip_content_4.png"
			mode="aspectFit"
		></image>
		<image
			style="width: 100vw; height: 494rpx; margin-top: 32rpx"
			src="https://mcdn.chatgk.com/xcx/static/images/vip/vip_content_5.png"
			mode="aspectFit"
		></image>

		<!-- <view v-if="userInfo.isVIP" class="flex-column view-bottom-open">
			<image style="margin: 20rpx 32rpx 0; width: 686rpx; height: 112rpx; z-index: 1;"
				src="https://mcdn.chatgk.com/xcx/static/images/vip/vip_open_btn.png" mode="aspectFit"></image>

			<view class="flex-row center-row center-column space-between"
				style="margin: -112rpx 72rpx 0; height: 112rpx; z-index: 2;">
				<view class="flex-row center-row" style="padding-top: 14rpx;">
					<text class="text-open-title">限时专享:{{productInfo.pricelocal ? productInfo.pricelocal:""}}</text>
					<text class="text-open-price">{{productInfo.price ? productInfo.price:"￥368"}}</text>
				</view>

				<text class="text-open-button" @tap="onClickOpenVip">立即开通</text>
			</view>
		</view> -->
		<loading v-show="loadshow"></loading>
	</view>
</template>

<script>
import { Iap, IapTransactionState } from '/common/request/iap.js';
import userManager from '@/common/manager/user-manager.js';
import AppPay from '@/common/request/appPay.js';
import xcxInfo from '@/common/manager/xcxInfo.js';

const appPay = new AppPay();
export default {
	data() {
		return {
			// 先拿code获取的openid
			openid: '',
			wxPlayData: {},
			loadshow: false,
			currency_symbols: {
				CNY: '￥',
				RMB: '￥',
				USD: '$', // US Dollar
				EUR: '€', // Euro
				CRC: '₡', // Costa Rican Colón
				GBP: '£', // British Pound Sterling
				ILS: '₪', // Israeli New Sheqel
				INR: '₹', // Indian Rupee
				JPY: '¥', // Japanese Yen
				KRW: '₩', // South Korean Won
				NGN: '₦', // Nigerian Naira
				PHP: '₱', // Philippine Peso
				PLN: 'zł', // Polish Zloty
				PYG: '₲', // Paraguayan Guarani
				THB: '฿', // Thai Baht
				UAH: '₴', // Ukrainian Hryvnia
				VND: '₫' // Vietnamese Dong
			},
			productInfo: {
				price: '￥368'
			},
			iap: Iap,
			loading: false,
			productId: '',
			productList: [],
			environment: null,
			userInfo: getApp().globalData.userInfo || {},
			equipment: '',
			chkiospay: false,
			name: xcxInfo.name,
			storeInfo: JSON.parse(uni.getStorageSync('storeInfo'))
		};
	},
	onLoad() {
		switch (uni.getSystemInfoSync().platform) {
			case 'android':
				this.environment = 'android';
				break;
			case 'ios':
				this.iap = new Iap({
					products: ['vip.volunteercard.388'] // 苹果开发者中心创建
				});
				this.environment = 'ios';
				this.init();
				break;
			default:
				console.log('运行在开发者工具上');
				break;
		}
	},
	onShow() {
		this.equipment = uni.getSystemInfoSync('systemInfo').osName;
		this.chkiospay = uni.getStorageSync('chkiospay');
	},

	methods: {
		// 点击返回
		onClickBack() {
			uni.navigateBack();
		},
		// 点击绑定会员卡
		onClickBindingCard() {
			if (this.$userManager.isLogin()) {
				uni.navigateTo({
					url: '/pages/login/binding-card'
				});
			}
		},
		async init() {
			// uni.showLoading({
			// 	title: ''
			// })
			if (this.environment != 'ios') return;

			try {
				// 初始化，获取iap支付通道
				await this.iap.init();

				// 从苹果服务器获取产品列表
				this.productList = await this.iap.getProduct();
				this.productList[0].checked = true;
				this.productId = this.productList[0].productid;
				this.productInfo = this.productList[0];

				const arr = this.productInfo.pricelocal.split('=') || [];

				let key = '';
				if (arr.length > 0) {
					key = arr[arr.length - 1];
				}

				key = this.currency_symbols[key] || '￥';
				this.productInfo['pricelocal'] = key;
			} catch (e) {
				uni.showModal({
					content: e.errMsg,
					showCancel: false
				});
			} finally {
				uni.hideLoading();
			}

			if (this.iap.ready) {
				// this.restore();
			}
		},
		async restore() {
			// 检查上次用户已支付且未关闭的订单，可能出现原因：首次绑卡，网络中断等异常
			// 在此处检查用户是否登陆
			// uni.showLoading({
			// 	title: '正在检测已支付且未关闭的订单...'
			// });

			try {
				// 从苹果服务器检查未关闭的订单，可选根据 username 过滤，和调用支付时透传的值一致
				const transactions = await this.iap.restoreCompletedTransactions();

				if (!transactions.length) {
					return;
				}

				// 开发者业务逻辑，从服务器获取当前用户未完成的订单列表，和本地的比较
				// 此处省略
				switch (transaction.transactionState) {
					case IapTransactionState.purchased:
						// 用户已付款，在此处请求开发者服务器，在服务器端请求苹果服务器验证票据
						//let result = await this.validatePaymentResult();

						// 验证通过，交易结束，关闭订单
						// if (result) {
						//   await this._iap.finishTransaction(transaction);
						// }
						break;
					case IapTransactionState.failed:
						// 关闭未支付的订单
						await this._iap.finishTransaction(transaction);
						break;
					default:
						break;
				}
			} catch (e) {
				uni.showModal({
					content: e.errMsg,
					showCancel: false
				});
			} finally {
				uni.hideLoading();
			}
		},
		fetchCreatWeChatOrderAPI() {
			let reqObj = {
				openid: this.openid,
				transactions: 'xcx',
				serviceId: this.storeInfo.vipserviceid
			};
			this.$request.creatWeChatOrderAPI(reqObj).then((res) => {
				if (res.code == 20000) {
					this.wxPlayData = res.data;
					wx.hideLoading();
					// 拿到参数调用微信支付接口
					wx.requestPayment({
						timeStamp: res.data.timeStamp + '',
						nonceStr: res.data.nonceStr,
						package: res.data.package,
						signType: 'MD5',
						paySign: res.data.paySign,
						success(res) {
							let visitor = uni.getStorageSync('visitorId') || {};
							if (visitor.visitorId) {
								visitor.buy = 1;
								this.$request.invitedNew(visitor).then((res) => {});
							}
							this.userInfo = getApp().globalData.userInfo;
							wx.showToast({
								title: '支付成功',
								icon: 'success',
								duration: 1000
							});
						},
						fail(res) {
							wx.showToast({
								title: '取消支付',
								icon: 'none',
								duration: 1000
							});
						}
					});
				}
			});
		},
		async onClickOpenVip() {
			if (this.equipment == 'ios' || this.equipment == 'macos') {
				uni.showToast({
					title: '当前ios设备不支持',
					icon: 'none'
				});
				return;
			}
			let that = this;
			if (!this.$userManager.isLogin()) {
				uni.navigateTo({
					url: '/pages/login/login-home'
				});
				return;
			}

			// 微信小程序支付
			// #ifdef  MP-WEIXIN
			wx.showLoading({
				title: '加载中...'
			});
			wx.login({
				success: (res) => {
					let userCode = res.code;
					// 将code传递给服务器
					this.$request
						.getWeChatAccessTokenXcx({
							code: userCode
						})
						.then((res) => {
							if (res.code == 20000) {
								this.openid = res.data.openid;
								this.fetchCreatWeChatOrderAPI();
							}

							// this.wxPlay = res.data
						});
				}
			});
			// #endif

			// #ifdef APP-PLUS || H5
			if (this.environment == 'android') {
				// 发起微信支付
				appPay
					.wxPay()
					.then((resData) => {
						let { res, orderInfo } = resData;
						that.$request
							.verifyWXPay({
								out_trade_no: orderInfo
							})
							.then((res) => {
								let visitor = uni.getStorageSync('visitorId') || {};
								if (visitor.visitorId) {
									visitor.buy = 1;
									api.invitedNew(visitor).then((res) => {});
								}
								this.userInfo = getApp().globalData.userInfo;
							});
					})
					.catch((err) => {});
			} else {
				if (this.productInfo && Object.keys(this.productInfo).length > 0) {
					if (this.loading == true) {
						return;
					}
					this.loading = true;

					// 请求苹果支付
					// uni.showLoading({
					// 	title: '购买中...',
					// 	mask: true
					// })

					try {
						const transaction = await this.iap.requestPayment({
							productid: this.productInfo.productid
							// manualFinishTransaction: true,
						});

						// 支付成功

						// uni.showLoading({
						// 	title: '',
						// 	mask: true
						// })
						this.loadshow = true;
						this.$request
							.verify({
								appid: '6446615912',
								receipt: transaction.transactionReceipt,
								consume: 1
							})
							.then((res) => {
								this.loadshow = false;
								uni.hideLoading();
								uni.showToast({
									title: '购买成功',
									icon: 'success'
								});
								let visitor = uni.getStorageSync('visitorId') || {};
								if (visitor.visitorId) {
									visitor.buy = 1;
									this.$request.invitedNew(visitor).then((res) => {});
								}

								this.userInfo = getApp().globalData.userInfo;
							})
							.catch((err) => {
								uni.hideLoading();
							});
					} catch (e) {
						uni.hideLoading();
						if (e.code != -100 && e.code != 2) {
							uni.showModal({
								content: e.errMsg,
								showCancel: false
							});
						}
					} finally {
						this.loading = false;
						uni.hideLoading();
					}
				} else {
					uni.showToast({
						title: '商品尚未准备好！',
						icon: 'none'
					});
				}
			}
			// #endif
		}
	}
};
</script>

<style lang="scss" scoped>
.openMembership {
	background-color: #f8f8f8;
	padding-bottom: 150rpx;
}

.header {
	display: flex;
	flex-direction: row;
	align-items: center;

	.center-column {
		display: flex;
		flex-direction: row;
		align-items: center;
	}
}

.lijikaitong {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	position: fixed;
	bottom: -130rpx;
	left: 8%;
}
.vip_noPrice_img {
	position: relative;
}
.vip_price {
	position: absolute;
	left: 10%;
	top: 36%;
}
.zhiyuankaPrice {
	font-size: 60rpx;
	color: #fefbe5;
	font-weight: bold;
}
.vipprice {
	font-size: 40rpx;
	color: #bf7c34;
	text-decoration: line-through;
}

.lighting {
	width: 30px;
	height: 74px;
	position: relative;
	top: -55px;
	left: -80px;
	transform: rotate(15deg);
	-webkit-transform: rotate(15deg);
	-webkit-animation: lighting 1.2s linear infinite forwards;
	-moz-animation: lighting 1.2s linear infinite forwards;
	animation: lighting 1.2s linear infinite forwards;
	background: rgba(255, 255, 255, 0.4);
	z-index: 1;
}

@keyframes lighting {
	from {
		left: -80px;
		/* 起始位置 */
	}

	to {
		left: calc(100% + 80px);
		/* 结束位置，需根据实际情况调整偏移量 */
	}
}

.text-nav-title {
	color: #333333;
	font-size: 16px;
	font-weight: 600;
	margin-left: 8rpx;
}

.text-nav-right {
	width: 140rpx;
	height: 50rpx;
	line-height: 50rpx;
	color: #ff3b0a;
	font-size: 11px;
	font-weight: 600;
	text-align: center;
	border: 2rpx solid #ff3b0a;
	border-radius: 30rpx;
}

.view-bottom-open {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	height: calc(env(safe-area-inset-bottom) + 112rpx + 40rpx);
	background-color: #fff;
	box-shadow: -6rpx 6rpx 14rpx rgba(0, 0, 0, 0.4);
}

.text-open-title {
	color: #fff;
	font-size: 28rpx;
	font-weight: bold;
}

.text-open-price {
	color: #fff;
	font-size: 48rpx;
	font-weight: bold;
}

.text-open-button {
	margin-top: -108rpx;
	height: 108rpx;
	line-height: 108rpx;
	color: white;
	font-size: 48rpx;
	font-weight: bold;
	z-index: 2;
}
</style>
